package com.qianchang.microfinance.view.manager;

import android.content.Context;
import android.graphics.Bitmap;

import com.qianchang.microfinance.bean.ProveImageInfo;
import com.qianchang.microfinance.utils.ErrorManager;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.ToastUtil;
import com.google.gson.Gson;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * 版权:深圳市迪蒙网络科技有限公司
 * 描述: 这个类继承于ChoseImageManager，在选择完图片之后，该类选择了对图片进行上传的操作,图片上传成功之后
 * 调用onUploadImageFileSuccess方法，通知子类去做别的事情
 * 修改人:<修改人>
 * Created by 朱成 on 2016/12/19.
 */

public abstract class UploadImageChooseImageManager extends ChooseImageManager {

    public UploadImageChooseImageManager(Context context) {
        super(context);
    }

    @Override
    protected void onPhotoResult(Bitmap bitmap) {
        uploadImage(bitmap);
    }

    private void uploadImage(Bitmap bitmap) {
        // 拍照后，不选用图片，bitmap会为空
        if (bitmap == null)
            return;
        final String photoPath = super.createFile(bitmap);

        File file = new File(photoPath);
        Map<String, File> files = new HashMap<>();
        files.put(file.getName(), file);
        Map<String, String> fileParamsMap = new HashMap<>();
        fileParamsMap.put("allowFile", "jpg,png");
        DMOKHttpUtils.getInstance().uploadFile(mContext, getUrl(), fileParamsMap, "uploadFile", files, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                if (response.isReqDataSuccess()) {
                    ProveImageInfo provinceInfo = parseJson(response.getObject());
                    onUploadImageFileSuccess(provinceInfo);
                } else {
                    onUploadImageFileFailure(ErrorManager.getDescription(response.getCode()));
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.getInstant().show(mContext, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    protected abstract void onUploadImageFileSuccess(ProveImageInfo provinceInfo);

    protected abstract void onUploadImageFileFailure(String msg);


    private ProveImageInfo parseJson(String data) {
        return new Gson().fromJson(data, ProveImageInfo.class);
    }

    /**
     * 上传图片的url
     *
     * @return
     */
    protected abstract String getUrl();

}
